package com.lc.tgxm.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.lc.tgxm.BaseApplication;
import com.lc.tgxm.R;
import com.lc.tgxm.adapter.PhotoPagerAdapter;
import com.lc.tgxm.util.GLobalConstant;
import com.lc.tgxm.util.PhotoViewInterface;
import com.lc.tgxm.widget.ViewPagerFixed;
import com.zcx.helper.util.UtilFile;
import com.zcx.helper.util.UtilToast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;


/**
 * 图片查看类
 */
public class PhotoActivity extends BaseActivity {
    private int mPosition;
    private ArrayList<PhotoViewInterface> list;
    private TextView mPhotoTvPosition;
    private final int MSG_SUC = 1;
    private final int MSG_ERROR = 2;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SUC:
                    UtilToast.show("保存成功");
                    break;
                case MSG_ERROR:
                    UtilToast.show("保存失败");
                    break;
            }
            return false;
        }
    });


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);// 去掉信息栏
        setContentView(R.layout.activity_photo);

        Intent intent = getIntent();
        mPosition = intent.getIntExtra("position", 0);
        // noinspection unchecked
        list = (ArrayList<PhotoViewInterface>) intent.getSerializableExtra("list");
        initView();
    }

    private void initView() {
        mPhotoTvPosition = (TextView) findViewById(R.id.photo_tv_position);
        mPhotoTvPosition.setText(mPosition + 1 + "/" + list.size());

        final ViewPagerFixed mPhotoVpVp = (ViewPagerFixed) findViewById(R.id.photo_vp_vp);
        mPhotoVpVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(final int position) {
                mPhotoTvPosition.setText(position + 1 + "/" + list.size());
                mPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        mPhotoVpVp.setAdapter(new PhotoPagerAdapter(list, PhotoActivity.this));
        mPhotoVpVp.setCurrentItem(mPosition);

        ImageView mPhotoIvXiazai = (ImageView) findViewById(R.id.photo_iv_xiazai);
        mPhotoIvXiazai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onDownLoad(list.get(mPosition).getPicUrl());
            }
        });
    }

    private class DownLoadImageService implements Runnable {
        private String url;

        public DownLoadImageService(String url) {
            this.url = url;
        }

        @Override
        public void run() {
            Bitmap bitmap;
            boolean result = false;
            try {
                bitmap = Glide.with(context)
                        .load(url)
                        .asBitmap()
                        .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                        .get();
                if (bitmap != null) {
                    // 在这里执行图片保存方法
                    result = saveImageToGallery(bitmap);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (result) {
                    // 图片保存成功
                    handler.sendEmptyMessage(MSG_SUC);
                } else {
                    // 图片保存失败
                    handler.sendEmptyMessage(MSG_ERROR);
                }
            }
        }

        // 保存图片
        public boolean saveImageToGallery(Bitmap bmp) {
            boolean result = false;
            // 创建保存图片的文件夹
            String folder = BaseApplication.INSTANCE.getAppFolder() + File.separator + GLobalConstant.PHOTO_FODLER;
            if (UtilFile.createPathFile(folder)) {
                String fileName = System.currentTimeMillis() + ".jpg";
                File currentFile = new File(folder, fileName);

                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(currentFile);
                    bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (fos != null) {
                            fos.close();
                        }
                        bmp.recycle();
                        result = currentFile.exists();
                        if (result) {
                            // 最后通知图库更新
                            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(currentFile)));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return result;
        }

    }

    /**
     * 启动图片下载线程
     */
    private void onDownLoad(String url) {
        UtilToast.show("正在保存图片");
        DownLoadImageService service = new DownLoadImageService(url);
        // 启动图片下载线程
        new Thread(service).start();
    }
}
